import Taro from "@tarojs/taro";

type Options = {
    timeout:number,
    baseUrl:string,
    method:keyof Taro.request.Method
}
Taro.addInterceptor(Taro.interceptors.logInterceptor);
Taro.addInterceptor(Taro.interceptors.timeoutInterceptor);

function createRequest(options:Options){

    const { baseUrl,timeout,method } = options;

    return (url:string,data)=>{
        return new Promise((resolve,reject)=>{
            Taro.request({
                url:`${baseUrl}/${url}`,
                method:method,
                timeout,
                header: {
                    "content-type": "application/json" 
                },
                data,
                success:(res)=>{
                    console.log(res.data);
                    resolve(res.data);
                },
                fail:(err)=>{
                    console.log(err);
                    reject(err);
                }
            });
        });
    };

    
}

export const get = createRequest({
    baseUrl:BASE_URL,
    timeout:5000,
    method:"GET"
});

export const post = createRequest({
    baseUrl:BASE_URL,
    timeout:5000,
    method:"POST"
});

export const put = createRequest({
    baseUrl:BASE_URL,
    timeout:5000,
    method:"PUT"
});